package com.sskj.fabi.ui.activity;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.IAsyncDataSource;
import com.shizhefei.mvc.IDataAdapter;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.mvc.MVCNormalHelper;
import com.shizhefei.mvc.RequestHandle;
import com.shizhefei.mvc.ResponseSender;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.IntentUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.OrderDetailBean;
import com.sskj.fabi.bean.PayTypeBean;
import com.sskj.fabi.bean.PayTypeEnum;
import com.sskj.fabi.presenter.FabiOrderDetailActivityPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.mvchelper.LoadViewFactory;
import com.sskj.lib.mvchelper.NormalRefreshDataSource;
import com.sskj.lib.mvchelper.RefreshDataSource;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.FABI_ORDER_DETAIL)//订单交易
public class FabiOrderDetailActivity extends BaseActivity<FabiOrderDetailActivityPresenter> {

    @BindView(R2.id.ivBack)
    LinearLayout ivBack;
    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.tvOrderNum)
    TextView tvOrderNum;
    @BindView(R2.id.tvStatus)
    TextView tvStatus;
    @BindView(R2.id.tvOrderSummary)
    TextView tvOrderSummary;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvAllMoney)
    TextView tvAllMoney;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;


    @BindView(R2.id.tvPayCode)
    TextView tvPayCode;

    @BindView(R2.id.tvTime)
    TextView tvTime;
    @BindView(R2.id.llTime)
    LinearLayout llTime;
    @BindView(R2.id.tvContract)
    TextView tvContract;
    @BindView(R2.id.tvCancel)
    TextView tvCancel;
    @BindView(R2.id.btSubmit)
    Button btSubmit;
    @BindView(R2.id.recyclerViewPayType)
    RecyclerView recyclerViewPayType;
    @BindView(R2.id.llBottom)
    LinearLayout llBottom;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private ArrayList<PayTypeBean> payTypeBeans;
    private boolean isBuyer;
    OrderDetailBean data;
    @Autowired
    String id;
    private MaterialDialog pwdTip;
    private Disposable timerDispo;
    private SlimAdapter slimAdapterPayType;
    private SpannableStringBuilder spannableStringBuilder;
    private String time;
    private MaterialDialog appealTip;
    private Disposable detailDispo;
    private SlimAdapter<OrderDetailBean.StockUserPayWaysBean> slimAdapter;
    private int checkPos = -1;
    private boolean isFirst = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.fabi_activity_fabi_order_detail;
    }

    @Override
    public FabiOrderDetailActivityPresenter getPresenter() {
        return new FabiOrderDetailActivityPresenter();
    }

    @Override
    protected void initView() {
        setTitle("订单交易");
        ARouter.getInstance().inject(this);
        initPayType();
    }

    @Override
    protected void initData() {
//        refresh();
//        refreshTimerOrder();

        LoadViewFactory loadViewFactory = new LoadViewFactory();
        MVCCoolHelper mvcNormalHelper = new MVCCoolHelper<OrderDetailBean>(coolRefreshView, loadViewFactory.madeLoadView(), loadViewFactory.madeLoadMoreView());
        NormalRefreshDataSource<OrderDetailBean> normalRefreshDataSource = new NormalRefreshDataSource<OrderDetailBean>(coolRefreshView) {

            @Override
            public Flowable<OrderDetailBean> loadData() {
                return mPresenter.getData(id);
            }
        };
        mvcNormalHelper.setAdapter(new IDataAdapter<OrderDetailBean>() {
            @Override
            public void notifyDataChanged(OrderDetailBean o, boolean isRefresh) {
                updateUI(o);
            }

            @Override
            public OrderDetailBean getData() {
                return null;
            }

            @Override
            public boolean isEmpty() {
                return false;
            }
        });
        mvcNormalHelper.setDataSource(normalRefreshDataSource);
        mvcNormalHelper.refresh();
    }

    /**
     * 定时刷新订单信息
     */
    private void refreshTimerOrder() {
        DisposUtil.close(detailDispo);
        detailDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .subscribe(aLong -> {
                    mPresenter.getData(id, false);
                });

    }

    private void initPayType() {

        payTypeBeans = new ArrayList<>();
        payTypeBeans.add(new PayTypeBean(R.mipmap.fabi_icon_wx, "微信支付", true));
        payTypeBeans.add(new PayTypeBean(R.mipmap.fabi_icon_alipay, "支付宝支付", false));
        payTypeBeans.add(new PayTypeBean(R.mipmap.fabi_icon_yl, "银行卡支付", false));

        HashMap<String, PayTypeEnum> iconMap = new HashMap<>();
        iconMap.put(PayTypeEnum.WX.getType(), PayTypeEnum.WX);
        iconMap.put(PayTypeEnum.ALIPAY.getType(), PayTypeEnum.ALIPAY);
        iconMap.put(PayTypeEnum.YL.getType(), PayTypeEnum.YL);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_pay_type, new SlimInjector<OrderDetailBean.StockUserPayWaysBean>() {
            @Override
            public void onInject(OrderDetailBean.StockUserPayWaysBean data, IViewInjector injector, List payloads) {

                injector
                        .background(R.id.viewIcon, ContextCompat.getDrawable(App.INSTANCE, iconMap.get(data.getPayType()).getRes()))
                        .text(R.id.tvTitle, iconMap.get(data.getPayType()).getName() + "支付")
                        .checked(R.id.checkbox, data.isCheck());

            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (position == checkPos) {
                        return;
                    }
                    if (checkPos == -1) {
                        slimAdapter.getDataItem(position).setCheck(true);
                        slimAdapter.notifyItemChanged(position);
                        checkPos = position;
                    } else {
                        slimAdapter.getDataItem(checkPos).setCheck(false);
                        slimAdapter.getDataItem(position).setCheck(true);
                        slimAdapter.notifyItemChanged(position);
                        slimAdapter.notifyItemChanged(checkPos);
                        checkPos = position;
                    }
                });

        recyclerViewPayType.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterPayType = SlimAdapter.create().register(R.layout.fabi_recy_item_pay_type_show, new SlimInjector<OrderDetailBean.StockUserPayWaysBean>() {
            @Override
            public void onInject(OrderDetailBean.StockUserPayWaysBean data, IViewInjector injector, List payloads) {

                if (PayTypeEnum.ALIPAY.getType().equals(data.getPayType())) {

                    injector
                            .visible(R.id.llQRCode)
                            .text(R.id.tvPayName, FabiOrderDetailActivity.this.data.getSellUsername())
                            .text(R.id.tvPayTypeTitle, "收款方式：")
                            .text(R.id.tvPayAccountTitle, "收款账户：")
                            .text(R.id.tvPayTitle, String.format("%s：%s    %s", "支付宝", data.getAlipayAccount(), FabiOrderDetailActivity.this.data.getSellUsername()))
                            .text(R.id.tvPayType, "支付宝")
                            .clicked(R.id.ivQRCode, v -> {
                                TipFabiUtil.showQR(FabiOrderDetailActivity.this, data.getAliImg(), "支付宝扫一扫，向他付款");
                            });
                } else if (PayTypeEnum.WX.getType().equals(data.getPayType())) {
                    injector
                            .visible(R.id.llQRCode)
                            .text(R.id.tvPayName, FabiOrderDetailActivity.this.data.getSellUsername())
                            .text(R.id.tvPayTypeTitle, "收款方式：")
                            .text(R.id.tvPayAccountTitle, "收款账户：")
                            .text(R.id.tvPayTitle, String.format("%s：%s    %s", "微信", data.getWxAccount(), FabiOrderDetailActivity.this.data.getSellUsername()))
                            .text(R.id.tvPayType, "微信")
                            .clicked(R.id.ivQRCode, v -> {
                                TipFabiUtil.showQR(FabiOrderDetailActivity.this, data.getWxImg(), "微信扫一扫，向他付款");
                            });
                } else if (PayTypeEnum.YL.getType().equals(data.getPayType())) {
                    injector
                            .gone(R.id.llQRCode)
                            .text(R.id.tvPayName, FabiOrderDetailActivity.this.data.getSellUsername())
                            .text(R.id.tvPayTypeTitle, "银行卡类型：")
                            .text(R.id.tvPayAccountTitle, "收款账户：")
                            .text(R.id.tvPayTitle, String.format("%s：%s    %s", "银行卡", data.getBankCardNo(), FabiOrderDetailActivity.this.data.getSellUsername()))
                            .text(R.id.tvPayType, data.getBankCardOpenBank())
                    ;
                }
            }
        });
        slimAdapterPayType.attachTo(recyclerViewPayType).updateData(new ArrayList());

    }

    public void updateUI(OrderDetailBean data) {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        this.data = data;
        isBuyer = data.getBuyId().equals(SPUtil.get(SPConfig.ID, ""));

        ClickUtil.click(tvContract, () -> {
            IntentUtil.call(this, "123");
        });
        tvOrderNum.setText(data.getDealEntrustNo());
        Map<String, String> buyerMap = new HashMap<>();
        Map<String, String> sellerMap = new HashMap<>();
        buyerMap.put("1", "待付款");
        buyerMap.put("2", "等待对方放币");
        buyerMap.put("3", "已完成");
        buyerMap.put("4", "申诉中");
        buyerMap.put("5", "已取消");
        sellerMap.put("1", "等待对方付款");
        sellerMap.put("2", "待收款");
        sellerMap.put("3", "已完成");
        sellerMap.put("4", "申诉中");
        sellerMap.put("5", "已取消");
        tvStatus.setText(isBuyer ? buyerMap.get(data.getStatus()) : sellerMap.get(data.getStatus()));
        tvOrderSummary.setText(String.format("您向%s%s%sUSDT",
                isBuyer ? data.getSellUsername() : data.getBuyUsername(),
                isBuyer ? "购买" : "出售",
                data.getTotalNum()));
        tvPrice.setText(data.getPrice() + "CNY");
        tvAllMoney.setText(data.getTotalPrice() + "CNY");
        if (isBuyer) {//买家页面
            tvStatus.setText(buyerMap.get(data.getStatus()));
            switch (data.getStatus()) {
                case "1"://未支付

                    buyerUnPaySecond();

                    break;
                case "2"://等待放币
                    buyerWaitCoin();
                    break;
                case "4"://卖家申诉中
                    buyerAndSellerAppeal();
                    break;
                case "5"://订单取消
                    orderCancel();
                    break;
                case "3"://订单完成
                    orderComplete();
                    break;
            }
        } else {//卖家页面
            tvStatus.setText(sellerMap.get(data.getStatus()));
            switch (data.getStatus()) {
                case "1"://未支付
                    sellerUnPay();
                    break;
                case "2"://等待放币
                    sellerWaitCoin();
                    break;
                case "4"://卖家申诉中
                    buyerAndSellerAppeal();
                    break;
                case "5"://订单取消
                    orderCancel();
                    break;
                case "3"://订单完成
                    orderComplete();
                    break;
            }
        }
    }

    private void buyerAndSellerAppeal() {
        DisposUtil.close(detailDispo);
        DisposUtil.close(timerDispo);
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText("");
        tvTime.setText("");
        llBottom.setVisibility(View.GONE);
        btSubmit.setVisibility(View.GONE);
    }

    private void orderComplete() {
        DisposUtil.close(detailDispo);
        DisposUtil.close(timerDispo);
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText("");
        tvTime.setText("");
        llBottom.setVisibility(View.GONE);
        btSubmit.setVisibility(View.GONE);
    }

    private void orderCancel() {
        DisposUtil.close(detailDispo);
        DisposUtil.close(timerDispo);
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText("");
        tvTime.setText("");
        llBottom.setVisibility(View.GONE);
        btSubmit.setVisibility(View.GONE);

    }

    private void sellerWaitCoin() {
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText(String.format("付款成功，付款参考号：（%s）", data.getRefer()));

        time = TimeFormatUtil.parseTime(data.getCountDownTime());
        spannableStringBuilder =
                new SpannableStringBuilder(String.format("系统将在%s后自动确认订单", time));
        spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvTime.setText(spannableStringBuilder);
        DisposUtil.close(timerDispo);
        timerDispo = Flowable.intervalRange(1, data.getCountDownTime(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getCountDownTime() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    time = TimeFormatUtil.parseTime(i);
                    spannableStringBuilder = new SpannableStringBuilder(String.format("系统将在%s后自动确认订单", time));
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    tvTime.setText(spannableStringBuilder);
                });

        llBottom.setVisibility(View.VISIBLE);
        tvCancel.setVisibility(View.VISIBLE);
        tvCancel.setText("申诉");
        btSubmit.setText("确认放币");
        btSubmit.setVisibility(View.VISIBLE);
        ClickUtil.click(tvCancel, () -> {
            appealTip = TipFabiUtil.showAppeal(this, (pos, reason) -> {
                appealTip.dismiss();
                mPresenter.allegeOrder(data.getId(), pos, reason);
            });
        });
        ClickUtil.click(btSubmit, () -> {
            pwdTip = TipFabiUtil.getPwdCheck(this, "支付密码", "请输入支付密码", pwd -> {
                pwdTip.dismiss();
                mPresenter.letGo(data.getId(), pwd);
            });
        });

    }

    private void buyerWaitCoin() {
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText(String.format("付款成功，付款参考号：（%s）", data.getRefer()));


        time = TimeFormatUtil.parseTime(data.getCountDownTime());
        spannableStringBuilder =
                new SpannableStringBuilder(String.format("系统将在%s后自动确认订单", time));
        spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvTime.setText(spannableStringBuilder);
        DisposUtil.close(timerDispo);
        timerDispo = Flowable.intervalRange(1, data.getCountDownTime(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getCountDownTime() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    time = TimeFormatUtil.parseTime(i);
                    spannableStringBuilder = new SpannableStringBuilder(String.format("系统将在%s后自动确认订单", time));
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    tvTime.setText(spannableStringBuilder);
                });


        llBottom.setVisibility(View.VISIBLE);
        tvCancel.setVisibility(View.GONE);
        btSubmit.setVisibility(View.GONE);
    }

    private void sellerUnPay() {
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
        slimAdapterPayType.updateData(data.getStockUserPayWays());
        tvPayCode.setText("");
        ClickUtil.click(tvCancel, () -> {
            TipUtil.getExitTip(this, "确认要取消订单", () -> {
                mPresenter.cancelOrder(data.getId());
            });
        });
        tvCancel.setText("取消订单");
        llBottom.setVisibility(View.VISIBLE);
        btSubmit.setVisibility(View.GONE);
    }

    private void buyerUnPaySecond() {
        isFirst = false;
        recyclerView.setVisibility(View.GONE);
        recyclerViewPayType.setVisibility(View.VISIBLE);
//        ArrayList<OrderDetailBean.StockUserPayWaysBean> stockUserPayWaysBeans = new ArrayList<>();
//        stockUserPayWaysBeans.add(data.getStockUserPayWays().get(checkPos));
        slimAdapterPayType.updateData(data.getStockUserPayWays());

        tvTime.setText("");
        tvPayCode.setText(String.format("待付款,请于%s内向%s支付,付款参考号：(%s)", TimeFormatUtil.parseTime(data.getCountDownTime()), data.getSellUsername(), data.getRefer()));
        ClickUtil.click(tvCancel, () -> {
            TipUtil.getExitTip(this, "确认要取消订单", () -> {
                mPresenter.cancelOrder(data.getId());
            });
        });
        tvCancel.setText("取消订单");
        llBottom.setVisibility(View.VISIBLE);
        btSubmit.setText("标记已付款");
        ClickUtil.click(btSubmit, () -> {
            mPresenter.markPay(data.getId());
//            pwdTip = TipFabiUtil.getPwdCheck(this, "支付密码", "请输入支付密码", pwd -> {
//                pwdTip.dismiss();
//            });
        });
        DisposUtil.close(timerDispo);
        timerDispo = Flowable.intervalRange(1, data.getCountDownTime(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getCountDownTime() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    tvPayCode.setText(String.format("待付款,请于%s内向%s支付,付款参考号：(%s)", TimeFormatUtil.parseTime(i), data.getSellUsername(), data.getRefer()));
                });

    }

    private void buyerUnPay() {
        recyclerView.setVisibility(View.VISIBLE);
        recyclerViewPayType.setVisibility(View.GONE);
        List<OrderDetailBean.StockUserPayWaysBean> stockUserPayWays = data.getStockUserPayWays();
        if (checkPos != -1) {
            stockUserPayWays.get(checkPos).setCheck(true);
        }
        slimAdapter.updateData(stockUserPayWays);

        tvPayCode.setText("");
        time = TimeFormatUtil.parseTime(data.getCountDownTime());
        spannableStringBuilder =
                new SpannableStringBuilder(String.format("系统将在%s后自动取消订单", time));
        spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvTime.setText(spannableStringBuilder);
        ClickUtil.click(tvCancel, () -> {
            TipUtil.getExitTip(this, "确认要取消订单", () -> {
                mPresenter.cancelOrder(data.getId());
            });
        });
        tvCancel.setText("取消订单");
        llBottom.setVisibility(View.VISIBLE);
        btSubmit.setText("立即支付");
        ClickUtil.click(btSubmit, () -> {
            if (checkPos != -1) {
                buyerUnPaySecond();
            }
        });
        DisposUtil.close(timerDispo);
        timerDispo = Flowable.intervalRange(1, data.getCountDownTime(), 0, 1, TimeUnit.SECONDS)
                .map(i -> data.getCountDownTime() - i)
                .compose(RxSchedulersHelper.transformer())
                .subscribe(i -> {
                    time = TimeFormatUtil.parseTime(i);
                    spannableStringBuilder =
                            new SpannableStringBuilder(String.format("系统将在%s后自动取消订单", time));
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(App.INSTANCE, R.color.fabi_f53)), 4, time.length() + 4, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    tvTime.setText(spannableStringBuilder);
                });

    }

    public void refresh() {
        mPresenter.getData(id, true);
    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(timerDispo);
        DisposUtil.close(detailDispo);

        super.onDestroy();
    }
}
